import subprocess
import time
import requests
import configparser
import pdb
import threading
from loguru import logger
import os
import shutil
from datetime import datetime

class AutoRun:
    def __init__(self):
        self.config = 'conf/mongo.ini'
        self.url = ''
        self.url_bev = ''
        self.user = ''
        self.pwd = ''
        self.user_names = []
        self.aibs_num = 0
        self.lcs_num = 0
        self.configInfo = dict()
        self.solutions = ''
        self.lcs_env = ''
        self.logging = logger.opt()
        self.logging.add(sink=open(f'./auto.log', 'w', encoding='UTF-8'),
                format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", 
                enqueue=True)

    # 解析配置文件
    def get_config(self):
        config = configparser.ConfigParser()
        config.read(self.config)
        try:
            self.user = config.get('jenkins_userInfo', 'aibs_user')
            self.pwd = config.get('jenkins_userInfo', 'aibs_pwd')
            self.url = config.get('jenkins_url', 'aibs')
            self.url_bev = config.get('jenkins_url', 'bev_aibs')
            self.lcs_env = config.get('auto_run', 'lcs_env')
            self.solutions = config.get('auto_run', 'solutions').split(',')
            self.user_names = config.get('auto_run', 'user_name').split(',')
        except Exception as e:
            self.logging.error(f'配置文件异常：{e}')
            raise Exception(f'配置文件异常：{e}')

    # 获取Jenkins信息
    def getJenkinsInfo(self,url,flag='json'):
        try:
            self.logging.info(f'发起请求：{url}')
            response = requests.get(url, auth=(self.user, self.pwd))
            if response.status_code == 200:
                if flag == 'text':
                    job_info = response.text.encode('utf-8')
                    return job_info
                else:
                    job_info = response.json()
                    return job_info
            else:
                self.logging.error(f'获取Jenkins信息异常！错误码: {response.status_code}')
                raise Exception(f'获取Jenkins信息异常！错误码: {response.status_code}')
        except Exception as e:
            self.logging.error(f'Jenkins连接失败！ error:{e}')
            raise Exception(f'Jenkins连接失败！ error:{e}')

    # 执行git命令
    def run_git(self, com):
        try:
            self.logging.info(f"执行：{com}")
            subprocess.check_output(com, shell=True)
            time.sleep(5)
            return True
        except subprocess.CalledProcessError:
            return False

    # 更新git仓
    def sync_git(self):
        if self.run_git('git fetch') and self.run_git('git pull'):
            path = os.getcwd()
            os.chdir('TestCase')
            self.logging.info(f"当前工作目录：{os.getcwd()}")

            self.run_git('git fetch')
            self.run_git('git pull')
            os.chdir(path)
            self.logging.info(f"当前工作目录：{os.getcwd()}")

    # 监控构建号
    def check_lib(self, aibs_lib):
        self.get_config()
        if aibs_lib == 0:
            aibs_lib = self.getJenkinsInfo(f'{self.url}/api/json')["lastBuild"]["number"]
        info = self.getJenkinsInfo(f'{self.url}/{aibs_lib}/api/json')
        if info["result"] == 'SUCCESS' and info['actions'][0]['causes'][0]['userName'] in self.user_names:
            data = self.getJenkinsInfo(f'{self.url}/{aibs_lib}/consoleFull',flag='text')
            if '--lcsid ' in str(data):
                lcs_lib = str(data).split('--lcsid ')[1].split(' ')[0]
            else:
                lcs_lib = self.lcs_num
                self.logging.warning(f"AIBS--{aibs_lib}没有检测到lcsid，将使用LCS--{self.lcs_num}执行！")
            if aibs_lib != 0 and aibs_lib != self.aibs_num:
                self.aibs_num = aibs_lib
                if lcs_lib:
                    self.lcs_num = lcs_lib
                self.logging.critical(f"检测到新版本：AIBS--{self.aibs_num}\tLCS--{self.lcs_num}")
                return True
        self.logging.info(f"未检测到AIBS有新构建，目前版本：AIBS--{self.aibs_num}\tLCS--{self.lcs_num}")
        return False
    
    # 同步资源
    def get_filter_com(self, solution):
        com = ''
        with open(solution, mode='r') as f:
            info = f.readlines()
            for i in info:
                if 'SUITE' in i and "@" not in i:
                    com =  i.split(':')[1].strip().split(',')[0:3]
                    commend = ['python3', 'Run_Mongo.py', '-f', f'{com[0]}', '-C', f'{com[1]}', '-a', f'{com[2]}', '-D', '0']
                    self.logging.critical(f"同步资源：{commend}")
                    subprocess.run(commend)
                    break
    
    # 保存测试报告
    def rename_reuslt(self, path):
        solution = path.split('/')[-1]
        name1 = f'workspace/{solution}'
        name2 = f'workspace/{self.aibs_num}/{datetime.now().strftime("%Y%m%d%H%M%S")}_{solution}'
        if os.path.exists(name1):
            os.makedirs(os.path.dirname(name2), exist_ok=True)
            shutil.move(name1, name2)
            self.logging.info(f"执行报告：{name2}")
        else:
            self.logging.error(f'未找到执行报告文件夹：{name1}')

    # 执行mongo命令
    def execute(self, aibs_lib=0):
        if self.check_lib(aibs_lib):
            self.sync_git()
            if len(self.solutions) > 0:
                self.get_filter_com(self.solutions[0])
                for solution in self.solutions:
                    com = ['python3', 'Run_Mongo.py', '-c', f'{solution.strip()}', '-J',f'{self.aibs_num}-{self.lcs_num}', '-M', '-D', '1', '-p', self.lcs_env]
                    self.logging.critical(f"开始执行命令：{' '.join(com)}")
                    subprocess.run(com)
                    time.sleep(30)
                    self.rename_reuslt(solution)
                    self.logging.info("执行结束！")

    # 定时器执行
    def run(self):
        self.execute()
        timer = threading.Timer(600, self.run)
        timer.start()


if __name__ == '__main__':
    test = AutoRun()
    test.run()
    # test.execute()
